import { _decorator, Component, Node, game } from "cc";
import Logger from "../utils/Logger";
const { ccclass, property } = _decorator;

@ccclass("BusyIndicator")
export class BusyIndicator extends Component {
    @property(Node)
    private mask!: Node;
    @property(Node)
    private loading!: Node;
    private loading_rotate: number = 0;

    static instance: BusyIndicator;
    private isBusy = false;

    onLoad() {
        if (BusyIndicator.instance) {
            if (BusyIndicator.instance !== this) {
                const errStr = "重复创建 BusyIndicator";
                Logger.error(errStr);
            } else {
                Logger.error("game 中只需一个BusyIndicator对象便可。");
            }
            return;
        }

        BusyIndicator.instance = this;
        game.addPersistRootNode(this.node);
        this.setIsBusy(false);
    }

    setIsBusy(isBusy: boolean) {
        this.isBusy = isBusy;
        if (this.isBusy) {
            this.scheduleOnce(() => {
                if (this.isBusy) {
                    this.mask.active = true;
                    this.loading.active = true;
                }
            }, 1.5);
        } else {
            this.mask.active = false;
            this.loading.active = false;
        }
    }

    update(dt: number) {
        if (this.isBusy) {
            this.loading_rotate += dt * 220;
            this.loading!.setRotationFromEuler(0, 0, -this.loading_rotate % 360);
            if (this.loading_rotate > 360) {
                this.loading_rotate -= 360;
            }
        }
    }
}
